package com.novel.service;


import com.novel.mapper.NovelMapper;
import com.novel.mapper.NovelShelfMapper;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.novel.NovelShelf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class NovelShelfService {

    @Autowired
    private NovelShelfMapper shelfMapper;

    @Autowired
    private NovelMapper novelMapper;

    /**
     * 根据用户id查询，用户的书架中有那些书籍
     * 也就是根据用户id查询用户书架信息
     *
     * @param userId 用户id
     */
    public List<Novel> findNovelByUserId(String userId) {
        //创建集合封装数据
        List<Novel> list = new ArrayList<>();
        //创建查询条件，封装数据
        NovelShelf record = new NovelShelf();
        record.setUserId(userId);
        //查询用户所有的阅读记录
        List<NovelShelf> recordList = shelfMapper.select(record);
        //遍历结合查询数据
        recordList.forEach(NovelShelf -> {
            //查询对应的小说信息
            Novel novel = novelMapper.selectByPrimaryKey(NovelShelf.getNovelId());
            //封装阅读到那里了
            novel.setNovelOrder(NovelShelf.getChapterOrder());
            list.add(novel);
        });
        return list;
    }

    /**
     * 添加书架信息
     *
     * @param shelf 书架信息
     */
    public boolean addNovelToShelf(NovelShelf shelf) {
        return shelfMapper.insert(shelf) == 1;
    }

    /**
     * 更新书架信息
     * 在用户阅读小说点击下一章之后需要更新
     *
     * @param shelf 书架信息
     */
    public boolean updateShelf(NovelShelf shelf) {
        return shelfMapper.updateByPrimaryKeySelective(shelf) == 1;
    }

    /**
     * 根据用户id查询用户书架信息
     *
     * @param userId 用户id
     */
    public List<NovelShelf> findUserShelf(String userId) {
        Example example = new Example(NovelShelf.class);
        example.createCriteria().andEqualTo("userId", userId);
        return shelfMapper.selectByExample(example);
    }

    /**
     * 根据传入的书架对象删除对应的书架信息
     *
     * @param shelf 书架对象，用来封装数据，必须要有用户id以及书籍id
     */
    public boolean deleteShelf(NovelShelf shelf) {
        return shelfMapper.delete(shelf) == 1;
    }
}
